package servlet.info_register;

import utility.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet{
    private static final long serialVersionUID=1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        User user=new User();

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try{
            con= DriverManager.getConnection("jdbc:mysql://localhost:3306/photo_project?characterEncoding=utf-8", "root", "mrt286933605");
            String uname=req.getParameter("userName");
            String upwd=req.getParameter("userPwd");
            ps=con.prepareStatement("select * from user where user_name=? and user_password=?");
            ps.setString(1,uname);
            ps.setString(2,upwd);
            rs=ps.executeQuery();
            if(rs.next()){
                user.setUid(rs.getInt(1));
                user.setUname(rs.getString(2));
                user.setUpwd(rs.getString(3));
                req.setAttribute("user",user);
                rs.close();
                con.close();
                ps.close();
                req.getRequestDispatcher("homePage.jsp").forward(req,resp);
            } else{
                rs.close();
                con.close();
                ps.close();
                resp.sendRedirect("userLogin.jsp");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
